package com.weipai.springboot.shiro;

import com.weipai.springboot.model.Admin;
import com.weipai.springboot.model.Customer;
import com.weipai.springboot.model.sys.User;
import com.weipai.springboot.module.dao.AdminDao;
import com.weipai.springboot.module.dao.CustomerDao;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * @author songmengqiang
 * @create 2018-08-20 15:55
 **/
@Component("authRealm")
public class AuthRealm extends AuthorizingRealm {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private AdminDao adminDao;
    @Autowired
    private CustomerDao customerDao;

    public void setAdminDao(AdminDao adminDao) {
        this.adminDao = adminDao;
    }

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    //认证.登录
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        int type = getUserType();

        String loginName;
        String password;
        String tokenPassword = new String((char[]) token.getCredentials());
        SimpleAuthenticationInfo simpleAuthenticationInfo = null;
        try {
            if (User.CUSTOMER == type) {
                Customer customer = customerDao.getCustomerByLoginName(usernamePasswordToken.getUsername());
                if (adminDao == null) {
                    return null;
                }


//            if (!tokenPassword.equals(customer.getCustomerPassword())) {
//                throw new IncorrectCredentialsException("用户名或密码错误！");
//            }
            loginName = customer.getCustomerLoginName();
            password = customer.getCustomerPassword();
        } else {
            Admin admin = adminDao.getAdminByLoginName(usernamePasswordToken.getUsername());
            if (admin == null) {
                return null;
            }
            loginName = admin.getAdminLoginName();
            password = admin.getAdminPassword();
        }

            simpleAuthenticationInfo = new SimpleAuthenticationInfo(
                    loginName,
                    tokenPassword,
                    ByteSource.Util.bytes(loginName),
                    getName()
            );
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("e"+e.getMessage());
        }
        return simpleAuthenticationInfo;
    }

    private int getUserType() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String typeStr = null;
        Enumeration headerNames = request.getHeaderNames();
        logger.info("headerNames:"+headerNames);
        while (headerNames.hasMoreElements()) {
            String key = (String) headerNames.nextElement();
            logger.info("key:"+key);
            if(key.equals(User.HEADER_TYPE_KEY)){
                typeStr = request.getHeader(key);
                 logger.info("typeStr:"+typeStr);
            }
        }
        int type = User.CUSTOMER;
        try {
           /* type = Integer.valueOf(typeStr);*/
            if(null!=typeStr){
                type = User.EMPLOYEE;
            }/*else{
                type = Integer.valueOf(typeStr);
            }*/
        } catch (NumberFormatException e) {
            e.printStackTrace();
            logger.error("e:"+e.getMessage());
            logger.error("invalid user-type value, default customer.");
        }

        return type;
    }
}
